package com.cloudlinkscm.base.filecenter.domain;

import com.cloudlinkscm.base.filecenter.common.FileUtil;
import com.cloudlinkscm.base.filecenter.constant.StorageTypeEnum;
import com.cloudlinkscm.base.filecenter.dao.FileRecordDao;
import com.cloudlinkscm.base.filecenter.model.FileRecord;
import com.cloudlinkscm.base.filecenter.model.bo.DocumentSaveBo;
import com.cloudlinkscm.loms.framework.util.BeanUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 抽象的文件记录manager
 *
 * @author : tac
 * @date : 2017/7/24
 */
public abstract class AbstractFileRecordManager {
    public FileRecordDao dao;

    public AbstractFileRecordManager(FileRecordDao dao) {
        this.dao = dao;
    }

    public FileRecord buildFileRecord(DocumentSaveBo bo, MultipartFile file, String location) {
        FileRecord record = new FileRecord();
        BeanUtils.copyProperties(bo, record);
        record.setName(FileUtil.getFileName(file.getOriginalFilename()));
        record.setExt(FileUtil.getFileExt(file.getOriginalFilename()));
        record.setStorageType(getStorageType().name());
        record.setSpaceUsage(calculateSpaceUsage(file));
        record.setDelete(false);
        record.setImage(false);
        record.setLocation(location);
        return record;
    }


    protected long calculateSpaceUsage(MultipartFile document){
        return document.getSize();
    }

    public abstract StorageTypeEnum getStorageType();

    public int delete(String id) {
        return delete(id, true);
    }

    public int delete(String id, boolean isLogic) {
        if(id == null){
            throw new IllegalArgumentException("id");
        }

        if(isLogic){
            FileRecord o = new FileRecord();
            o.setId(id);
            o.setDelete(true);
            return dao.updateByPrimaryKeySelective(o);
        }else {
            return dao.deleteByPrimaryKey(id);
        }
    }
}
